<?php
/**
 * 汇付商户进件
 * User: 13651
 * Time: 2025/10/22 10:55
 */

namespace App\Api\Controllers\HuiPay;

use App\Exceptions\BizException;
use App\Traits\HttpHelper;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class HuifuBaseController
{
    use HttpHelper;

    static $instance;

    protected $domain = 'https://api.huifu.com/v2/';

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 上传图片
     * @param array $config
     * @param string $file
     * @param array $params
     * @return string
     * @throws \Exception
     */
    public function picture(array $config, string $file,array $params)
    {
        $url = 'supplementary/picture';

        /**
         * 压缩图片
         */
        $img = '';
        try {
            //压缩图片
            $img_obj = Image::make($file);
            $fileName = basename($file, PATHINFO_EXTENSION);
            $img = public_path() . '/upload/s_images/';
            if (!is_dir($img)) {
                mkdir($img, 0777);
            }
            $img_obj->resize(800, 700);
            $img_obj->save($img . $fileName);
            $file = $img . $fileName;

            /**
             * 组装请求数据
             */
            $data = [
                'sys_id' => $config['sys_id'],
                'product_id' => $config['product_id'],
                'file' =>new \CURLFile($file,'',$fileName),
                'data'=>json_encode($params,JSON_UNESCAPED_UNICODE)
            ];
            return $this->sendFile($url, $data);
        } catch (\Exception $exception) {
            throw new \Exception("图片压缩异常：" . $exception->getMessage());
        }
    }

    /**
     * 组装请求数据
     * @param array $config
     * @param array $params
     * @return array
     * @throws BizException
     */
    protected function queryParams(array $config, array $params)
    {

        /**
         * 多层嵌套情况下 转化成json且不用排序
         */
        foreach ($params as $k => &$v) {
            if (is_array($v)) {
                $v = json_encode($v, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            }
        }

        $params = array_filter($params, function($v){
            if (!empty($v) || $v == '0') {
                return true;
            }
            return false;
        });

        ksort($params);

        /**
         * 生成签名
         */
        $sign = $this->createSign($params, $config['private_key']);

        /**
         * 组装请求数据
         */
        $data = [
            'sys_id' => $config['sys_id'],
            'product_id' => $config['product_id'],
            'sign' => $sign,
            'data' => $params,
        ];
        return $data;
    }

    /**
     * 生成签名
     * @param array $params
     * @param $rsaPrivateKey
     * @return string
     * @throws BizException
     */
    protected function createSign(array $params, $rsaPrivateKey)
    {

        $data = json_encode($params, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        $key = "-----BEGIN PRIVATE KEY-----\n" . wordwrap($rsaPrivateKey, 64, "\n", true) . "\n-----END PRIVATE KEY-----";

        $signature = '';
        try {
            openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256);
        } catch (\Exception $e) {
            Log::info('汇付支付渠道-生成签名异常' . $e->getMessage());
            throw new BizException("服务异常");
        }
        return base64_encode($signature);
    }

    /**
     * 发送POST请求
     * @param string $url
     * @param array $data
     * @return string
     * @throws BizException
     */
    protected function sendQuery(string $url, array $data)
    {
        $sendUrl = $this->domain . $url;
        Log::info('汇付支付渠道-请求url：' . $sendUrl);
        Log::info('汇付支付渠道-请求报文：', $data);
        try {
            $result = $this->sendPost($sendUrl, $data);
            $response = $result->getBody()->getContents();
            Log::info('汇付支付渠道-返回报文：' . $response);
        } catch (\Exception $e) {
            Log::info('汇付支付渠道-请求失败:' . $e->getMessage());
            throw new BizException("服务异常");
        }
        return $response;
    }

    /**
     * 发送POST-文件上传请求
     * @param string $url
     * @param array $data
     * @return string
     * @throws BizException
     */
    protected function sendFile(string $url, array $data)
    {
        $sendUrl = $this->domain . $url;
        Log::info('汇付支付渠道-请求url：' . $sendUrl);
        try {
            Log::info('汇付支付渠道-请求报文：', $data);
            $result = $this->sendFormDataPost($sendUrl, $data);
            Log::info('汇付支付渠道-返回报文：'.$result);
        } catch (\Exception $e) {
            Log::info('汇付支付渠道-图片上传请求失败:' . $e->getMessage());
            throw new BizException("服务异常");
        }
        return $result;
    }


    /**
     * 企业商户进件
     * @param array $config
     * @param array $params
     * @return string
     * @throws BizException
     */
    public function basicdataEnt(array $config,array $params)
    {
        $url = 'merchant/basicdata/ent';
        $query = $this->queryParams($config, $params);
        return $this->sendQuery($url, $query);
    }

    /**
     * 商户基本信息修改
     * @param array $config
     * @param array $params
     * @return string
     * @throws BizException
     */
    public function basicdataModify(array $config,array $params)
    {
        $url = 'merchant/basicdata/modify';
        $query = $this->queryParams($config, $params);
        return $this->sendQuery($url, $query);
    }

    /**
     * 商户详细信息查询
     * @param array $config
     * @param array $params
     * @return string
     * @throws BizException
     */
    public function basicdataQuery(array $config,array $params)
    {
        $url = 'merchant/basicdata/query';
        $query = $this->queryParams($config, $params);
        return $this->sendQuery($url, $query);
    }

    /**
     * 商户开通业务
     * @param array $config
     * @param array $params
     * @return string
     * @throws BizException
     */
    public function busiOpen(array $config,array $params)
    {
        $url = 'merchant/busi/open';
        $query = $this->queryParams($config, $params);
        return $this->sendQuery($url, $query);
    }

    /**
     * 申请单状态查询
     * PS：包含进件审核、实名认证状态、实名认证二维码
     * @param array $config
     * @param array $params
     * @return string
     * @throws BizException
     */
    public function statusQuery(array $config,array $params)
    {
        $url = 'merchant/basicdata/status/query';
        $query = $this->queryParams($config, $params);
        return $this->sendQuery($url, $query);
    }
}